<template>
  <div class="search-item search-select-tree-container">
    <el-input
      v-model="internalValue"
      :placeholder="placeholder"
      size="small"
      clearable
      @click.native="handleFocus"
      @blur="handleFocusLost"
    />
    <el-tree
      v-show="showTree"
      :id="treeId"
      ref="tree"
      class="selectTree-input floatTree"
      :style="'width:' + treeWidth"
      :highlight-current="true"
      :default-expand-all="true"
      :expand-on-click-node="false"
      :data="treeData"
      @node-click="handleSelectTreeNode"
    />
  </div>
</template>
<script>
export default {
  name: 'SearchSelectTree',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    treeId: {
      type: String,
      default: 'searchSelectTree'
    },
    treeWidth: {
      type: String,
      default: '220px'
    },
    treeData: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      showTree: false
    }
  },
  computed: {
    internalValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.$on('search-clear', function() {
      this.internalValue = ''
      this.showTree = false
    })
  },
  methods: {
    handleFocus() {
      this.showTree = true
    },
    handleFocusLost(e) {
      const isOther = e.relatedTarget == null || e.relatedTarget.closest('div.el-tree') == null || e.relatedTarget.closest('div.el-tree').id !== this.treeId

      if (isOther) {
        this.showTree = false
      } else {
        e.target.focus()
      }
    },
    handleSelectTreeNode(data) {
      this.internalValue = data.label
      this.showTree = false
      this.$emit('change', data)
    }
  }
}
</script>
<style scoped>
.floatTree {
  position: absolute;
  overflow: auto;
  z-index: 100;
  border: 1px solid #ddd;
  line-height: normal;
}
</style>
